import axios from 'axios'
import qs from 'qs'
import Cookie from 'js-cookie'
import hexMD5 from '../libs/md5.js'

const env = process.env.NODE_ENV
const baseHttp = process.env.API_HOST

const apiVersion = process.env.API_VERSION //  '/v1';
const apiSecret = process.env.API_SECRET

axios.defaults.baseURL = baseHttp;
axios.defaults.timeout = 30000;

axios.interceptors.request.use(function (httpRequest) {
  httpRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  if(httpRequest.method === 'post') {
    if (Cookie.get('token')) {
      httpRequest.headers['token'] = Cookie.get('token')
    }
    /*
    httpRequest.data = qs.stringify( {
      ...httpRequest.data
    })
    */
  }
  return httpRequest;
}, function (error) {
  //loadinginstace.close()
  return Promise.reject(error);
});

axios.interceptors.response.use(function (httpResponse) {
  if (process.env.DEBUG) {
    console.log(httpResponse)
  }
  return httpResponse;
}, function (error) {
  //loadinginstace.close()
  //Vue.$Message.error('请求出错了')
  return Promise.reject(error);
});

var api = {
  batch:(batchParams) => {
    var reqArr = []
    for(var key in batchParams) {
      reqArr.push(
        axios.post(apiVersion+batchParams[key].url, apiVersion+batchParams[key].params)
      )
    }
    return new Promise((resolve, reject) => {
      axios.all(reqArr).then((httpResponse) => {
        resolve(httpResponse)
      })
    })
  },
  get:(url, getParams) => {
    return new Promise((resolve, reject) => {
      //控制是否需要签名
      //params = api.addSign(params)
      //url = api.addUrlParts(url, urlParams)
      let runAxios = true
      if (process.env.DEBUG) {
        console.log('params start');
        console.log('get:'+apiVersion+url)
        console.log(getParams)
      }
      if (process.env.USE_MOCK) {
        let getApiData = require('./mock/async.js').default
        let apiData = getApiData(url)
        if (apiData) {
          resolve(apiData);
          runAxios = false
        }
      }
      if (runAxios) {
        axios.get(apiVersion+url, {params:getParams})
          .then(httpResponse => {
            resolve(httpResponse.data);
          })
          .catch((error) => {
            reject(error)
          })
      }
      })
  },
  post:(url, postParams) => {
    return new Promise((resolve, reject) => {
      //控制是否需要签名
      //params = api.addSign(params)
      //url = api.addUrlParts(url, urlParams)
      let runAxios = true
      if (process.env.DEBUG) {
        console.log('params start');
        console.log('post:' + apiVersion+url)
        console.log(postParams)
      }
      if (process.env.USE_MOCK) {
        let getApiData = require('./mock/async.js').default
        let apiData = getApiData(url)
        if (apiData) {
          resolve(apiData);
          runAxios = false
        }
      }
      if (runAxios) {
        axios.post(apiVersion+url, postParams)
          .then(httpResponse => {
            resolve(httpResponse.data);
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  },
  search:(baseUrl, urlParams, postParams) => {
    return new Promise((resolve, reject) => {
      //控制是否需要签名
      //params = api.addSign(params)
      let url = api.addUrlParts(baseUrl, urlParams)
      let runAxios = true
      if (process.env.DEBUG) {
        console.log('params start');
        console.log('post:' + apiVersion+url)
        console.log(postParams)
      }

      if (process.env.USE_MOCK) {
        let getApiData = require('./mock/async.js').default
        let apiData = getApiData(baseUrl)
        if (apiData) {
          resolve(apiData);
          runAxios = false
        }
      }
      if (runAxios) {
        axios.post(apiVersion+url, postParams)
          .then(httpResponse => {
            resolve(httpResponse.data);
          })
          .catch((error) => {
            reject(error)
          })
      }

      })
  },
  addUrlParts(url, urlParams) {
    var arr = []
    for (var key in urlParams) {
      arr.push(key+'='+urlParams[key])
    }
    return url + '?' + arr.join('&')
  },
  addSign:(params) => {
    var items = []
    params['time'] = parseInt(new Date().getTime() / 1000)
    params = api.objKeySort(params)
    for (let key in params) {
      items.push(key + params[key])
    }
    var str = apiSecret + items.join('') + apiSecret
    params['sign'] = hexMD5(str)
    return params
  },
  objKeySort:(obj) => { // 排序的函数
    var newkey = Object.keys(obj).sort()
    var newObj = {}
    for (var i = 0; i < newkey.length; i++) {
      newObj[newkey[i]] = obj[newkey[i]]
    }
    return newObj
  }
}

if (process.env.USE_MOCK) {
  require('./mock/index')
}

export default api
